package com.dongchedi.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.dongchedi.entity.CustomerLogin;
import com.dongchedi.entity.LoginTicket;
import com.dongchedi.service.FindLoginService;
import com.dongchedi.utils.CookieUtil;
import com.dongchedi.utils.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;
/**
  * @author leibidong
  * @description   登录拦截器
  * @date 2021/7/1
  */
@Component
public class LoginInterceptor implements HandlerInterceptor {

	@Autowired
	FindLoginService findLoginService;
	@Autowired
	HostHolder hostHolder;
	/*
	 * @Author: leibidong
	 * @Description: 拦截前置判断
	 * @Date: 2021/7/1 19:29
	 * @Param: [request, response, handler]
	 * @Return: boolean
	 **/
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler ) throws Exception {
		// 从 cookie 中获取登录凭证
		String ticket = CookieUtil.getValue(request, "ticket");
		if (ticket != null) {
			// 查询凭证
			LoginTicket loginTicket = findLoginService.findLoginTicket(ticket);
			// 检查凭证是否有效
			if (loginTicket != null && loginTicket.getStatus() == 1 && loginTicket.getExpired().after(new Date())) {
				// 根据凭证查询用户
				CustomerLogin customerLogin = findLoginService.queryCustomerLoginById(loginTicket.getUserId());
				// 在本次请求中持有用户--保存用户信息
				hostHolder.setUser(customerLogin);
			}else {
				JSONObject jsonObject=new JSONObject();
				jsonObject.put("code",0);
				jsonObject.put("msg","你还未登录，请先登录");
				jsonObject.put("data","");
				response.setContentType("text/html;charset=utf-8");
				PrintWriter out=response.getWriter();
				out.write(jsonObject.toJSONString());
				return false;
			}

		}
		return true;
	}
//调用controller之后执行
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//		CustomerLogin customerLogin = hostHolder.getUser();
//		if (customerLogin != null && modelAndView != null) {
//			modelAndView.addObject("loginUser", customerLogin);
//		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		hostHolder.clear();
	}
}
